import Ember from 'ember';
import Changeset from 'ember-changeset';
import ProjectValidations from '../../../validations/project';
import lookupValidator from 'ember-changeset-validations';

export default Ember.Controller.extend(ProjectValidations,{
  mainController: Ember.inject.controller('business.mainpage'),
  constants: Constants,
  queryCondition:'',
  flag:0,
  //已选项目
  chooseService:Ember.computed('projectInfo.services',function(){
    var serviceList=this.get('projectInfo.services');
    var name='';
    if(serviceList){
      serviceList=serviceList.sortBy('id');
      serviceList.forEach(function(service){
          name += service.get('item.name')+"，";
      });
      name=name.substring(0,name.length-1);
      return name;
    }else{
      return '无';
    }
  }),
  //所有项目
  allServiceList:Ember.computed('flag','serviceList','projectInfo','resultServiceList',function(){
    let _self = this;
    let allServiceList = new Ember.A();
    var serviceList=this.get('serviceList');
    let recommendServices = this.get('resultServiceList');
    if(!serviceList){
      return allServiceList;
    }
    if(!recommendServices){
      return allServiceList;
    }
    //方案中已经选择的护理项目
    var services=this.get('projectInfo.services');
    //全部的护理项目列表
    serviceList.forEach(function(service){
      var newObj = Ember.Object.create({
        id: service.get("id"),
        ent:service,
        hasChoosed:false,
        recommend:true,
      });
      if(service.get('countType.id')==164){
        newObj.set('count',true);
      }
      //将要显示的护理项目列表
      allServiceList.pushObject(newObj);
      //方案中已选项目标识
      if(services){
        services.forEach(function(serv){
          if(newObj.get("id")==serv.get("item.id")){
            newObj.set("hasChoosed",true);
            newObj.set('ent.period',serv.get('period'));
            newObj.set('ent.frequency',serv.get('frequency'));
          }

        });
      }
      //问卷推荐的护理项目列表，推荐项目字体变粗
        recommendServices.forEach(function(serv){
          if(_self.get('editMode')=="edit"){
            if(newObj.get("id")==serv.get("item.id")){
              newObj.set('strong',true);
              newObj.set('recommend',false);
            }else if(newObj.get("id")==serv.get("id")){
              newObj.set('strong',true);
              newObj.set('recommend',false);
            }
          }else{
            if(newObj.get("id")==serv.get("id")){
              newObj.set('strong',true);
              newObj.set('recommend',false);
            }
          }

        });
    });
    allServiceList = allServiceList.sortBy('recommend');
    return allServiceList;
  }),
  projectModel:Ember.computed('projectInfo',function(){
    var model = this.get("projectInfo");
    if (!model) {
        return null;
    }
    return new Changeset(model, lookupValidator(ProjectValidations), ProjectValidations);
  }),
  editService:false,
  detailEdit:false,
  actions:{
    toEva(){
      let id = this.get('resultID');
      this.get("mainController").switchMainPage('eva-check',{id:id,editMode:'edit'});
    },
    toEditService(){
      this.set('editService',true);
    },
    //选择项目
    chooseService(service){
      var _self=this;
      var arr=this.get('projectModel.services');
      let serviceArr = new Ember.A();
      if(arr){
        arr.forEach(function(service){
          serviceArr.pushObject(service);
        });
      }

      //寻找项目记录
      var findService = function(id){
        var item;
        arr.forEach(function(service){
          if(service.get('item.id')==id){
            item=service;
          }
        });
        return item;
      };
      if(service.hasChoosed){
        //将已选项目变为未选状态
        service.set('hasChoosed',false);

        var serviceItem = findService(service.get('ent.id'));
        //如果选择的是默认的已选项目，从数据中查找该条记录，并删除
        if(serviceItem&&serviceItem.get('id')){
          _self.store.findRecord('nursingprojectitem',serviceItem.get('id')).then(function(ser){
              ser.destroyRecord();
          });
        }else{
          //如果是后来添加的项目，将该条记录从项目数组中移除
          serviceArr.removeObject(serviceItem);
          _self.set('projectModel.services',serviceArr);
        }


      }else {

        //选择项目，并加入到项目数组
        var levelItem=this.store.createRecord('nursingprojectitem',{
          serviceId:service.get('ent.id'),
          project:_self.get('projectInfo'),
          item:service.get('ent')
        });
        if(service.get('ent.countType.id')==164){
          service.set('count',true);
        }
        service.set('hasChoosed',true);
        serviceArr.pushObject(levelItem);
        _self.set('projectModel.services',serviceArr);
      }
    },
    //保存
    detailSaveClick(){
      var _self=this;
      var editMode=this.get('editMode');
      var projectModel=this.get('projectModel');
      var services=this.get('projectModel.services');
      var count=0;
      let arr = new Ember.A();
      //循环存储services的每一项，然后在存储整个servicelevel
      services.forEach(function(service){
        let item = _self.store.peekRecord('customerserviceitem',service.get('serviceId'));
        console.log(item.get('name'));
        let ser = _self.store.createRecord('nursingprojectitem',{});
        ser.set('period',service.get('item.period'));
        ser.set('frequency',service.get('item.frequency'));
        ser.set('nursingproject',_self.get('projectModel'));
        ser.set('item',item);
        arr.pushObject(ser);
        // service.set('period',service.get('item.period'));
        // service.set('frequency',service.get('item.frequency'));
        // service.save();
        console.log('服务项目：',service);
        count++;
      });
      if(count==services.get('length')){
        projectModel.set('services',arr);
        projectModel.validate().then(function(){
          if(projectModel.get('errors.length')===0){
            App.lookup('controller:business.mainpage').openPopTip("正在保存");
            if(editMode=='add'){
              projectModel.set('delStatus',0);
              projectModel.save().then(function(){
                App.lookup('controller:business.mainpage').showPopTip("保存成功");
                var mainpageController = App.lookup('controller:business.mainpage');
                mainpageController.switchMainPage('nursingproject');
              });
            }else{
                projectModel.save().then(function(){
                  App.lookup('controller:business.mainpage').showPopTip("保存成功");
                  _self.set('detailEdit',false);
                  var route=App.lookup('route:business.mainpage.nursingproject-detail');
                  App.lookup('controller:business.mainpage').refreshPage(route);//刷新页面
                });
              }
          }else{
            projectModel.set("validFlag",Math.random());
          }
        });
      }

    },
    invalid(){},
    detailEditClick:function(){
      this.set('detailEdit',true);
      let serviceArray = new Ember.A();
      let projectInfo = this.get('projectInfo');
      let _self = this;
      _self.store.query('evaluateresult',{filter:{customer:{id:projectInfo.get('customer.id')}}}).then(function(questionnaireList){
        _self.set('questionnaireList',questionnaireList);
        let recentResult = _self.get('questionnaireList.lastObject');
        if(recentResult.get('score')){
          let score = recentResult.get('score');
          _self.store.query('nursinglevel',{filter:{'lowScore@$lte':score,'highScore@$gte':score}}).then(function(nursinglevel){
            let curLevel = nursinglevel.get('firstObject');
            let services = curLevel.get('services');
            services.forEach(function(service){
              serviceArray.pushObject(service);
              _self.incrementProperty('flag');
              _self.set('resultServiceList',serviceArray);
            });
          });
        }else{
          _self.store.query('evaluateexameranswer',{filter:{"[result][id]":recentResult.get('id')}}).then(function(answers){
            answers.forEach(function(answer) {
                //查询护理项目
                answer.get("answer").then(function(answers){
                  answers.get("services").then(function(services){
                    var len = services.get("length");
                    for(var i=0;i<len;i++){
                      var service = services.objectAt(i);
                      if (!serviceArray.findBy("id", service.get("id"))) {
                          serviceArray.pushObject(service);
                          _self.set('resultServiceList',serviceArray);
                          _self.incrementProperty("flag");

                      }
                    }
                  });

                });
            });
          });
        }
      });
      let serviceList=this.store.query('customerserviceitem',{}).then(function(services){
        _self.set("serviceList", services);
      });
    },//编辑按钮
    detailCancel:function(){
      var id=this.get('id');
      var editMode=this.get('editMode');
      if(id&&editMode=='edit'){
        this.set('detailEdit',false);
        this.get('projectInfo').rollbackAttributes();
        var route=App.lookup('route:business.mainpage.room-detail');
        App.lookup('controller:business.mainpage').refreshPage(route);//刷新页面
      }else{
        let mainpageController = App.lookup('controller:business.mainpage');
        mainpageController.switchMainPage('nursingproject');
      }
    },//取消按钮
    //删除按钮
    delById(){
      var _self = this;
      App.lookup('controller:business.mainpage').showConfirm("是否确定删除此记录",function(){
        _self.send('cancelPassSubmit',_self.get('projectInfo'));
      });
    },
    //弹窗取消
    invitation(){
      this.set('showpopInvitePassModal',false);
    },
    close(){
      this.set('editService',false);
    },
    //保存項目
    saveService(projectInfo){
      var _self=this;
      var services=this.get('projectInfo.services');
      var count=0;
        App.lookup('controller:business.mainpage').openPopTip("正在保存");
      services.forEach(function(service){
        service.set('frequency',service.get("frequency"));
        service.set('period',service.get("period"));
        service.save().then(function(serv){
        });
        count++;
      });
      if(count==services.get('length')){
        App.lookup('controller:business.mainpage').showPopTip("保存成功");
        _self.set('editService',false);

      }
    },
    //删除记录
    cancelPassSubmit(projectInfo){
      App.lookup('controller:business.mainpage').openPopTip("正在删除");
			this.set("showpopInvitePassModal",false);
      projectInfo.set("delStatus", 1);
      projectInfo.save().then(function() {
          App.lookup('controller:business.mainpage').showPopTip("删除成功");
          var mainpageController = App.lookup('controller:business.mainpage');
          mainpageController.switchMainPage('nursingproject');
      });
    }
  }
});
